/**
 * fileName: JsTree.java
 *     Date: 2012-6-25
 **/
package com.stranger.common.tag.jstree;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * @作者 stranger.lin
 *
 * @时间 2012-6-25
 */
public class JsTree extends TagSupport {

	private String id;
	private String url;
	
	
	
	private JspWriter out;
	/**
	 * 
	 */
	private static final long serialVersionUID = 2736125373203760325L;

	@Override
	public int doStartTag() throws JspException {
		try {
			out=pageContext.getOut();
			if (id==null||"".equals(id.trim())) {
				throw new JspException("id不能为空");
			}
			if (url==null||"".equals(url.trim())) {
				throw new JspException("url不能为空");
			}
			out.print("<div id=\""+id+"\"></div>");
			out.flush();
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		
		
		
		
		return EVAL_PAGE;
	}
	
	@Override
	public int doEndTag() throws JspException {
		
		try {
			StringBuffer js=new StringBuffer("$(function () {");
			js.append("$(\"#"+id+"\").jstree({\n");
			js.append("\"json_data\":{\n");
			js.append("\"ajax\":{\n");
			js.append("\"url\":\""+url+"\",");
			js.append("\"data\":function(n){ return { id : n.attr ? n.attr(\"id\") : 0 }; }");
			js.append("}}, \"plugins\" : [ \"themes\", \"json_data\" ]");
			js.append("});");
			out.print(js);
			out.flush();
			//System.err.println(js);
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		
		
		return EVAL_PAGE;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public static void main(String[] args) {
		try {
			new JsTree().doEndTag();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
